package com.lxk.controller;

import com.lxk.pojo.Auction;
import com.lxk.pojo.GoodsStat;
import com.lxk.pojo.Onsale;
import com.lxk.pojo.Seckill;
import com.lxk.service.AuctionService;
import com.lxk.service.GoodsStatService;
import com.lxk.service.OnsaleService;
import com.lxk.service.SeckillService;
import com.lxk.util.AuctionOrderTimerTask;
import com.lxk.util.AuctionPriceTimerTask;
import com.lxk.util.SeckillOrderTimerTask;
import com.lxk.vo.*;
import com.lxk.vo.result.CodeMsg;
import com.lxk.vo.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;

@Controller
public class ActivityController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private AuctionService as;
	@Autowired
	private GoodsStatService gss;
	@Autowired
	private SeckillService ss;
	@Autowired
	private OnsaleService os;

	/**
	 * 定时订单检查间隔30秒
	 */
	private final static long orderPeriod = 30*1000;
	
	/**
	 * 时间类型转换
	 * @param binder
	 */
	@InitBinder  
	public void initBinder(WebDataBinder binder) {  
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
	    dateFormat.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
	}

	/**
	 * 判断是否已存在拍卖
	 * @return
	 */
	@ResponseBody
	@GetMapping("/auction/test")
	public Result<Integer> getIsAuctionExist(){
		//设置新活动前，判断旧活动是否已结束，选择是否将旧活动取消
		if (gss.isAuctionExist()) {
			return Result.error(CodeMsg.AUCTION_NOT_EMPTY);
		}else{
			return Result.success(1);
		}
	}

	/**
	 * 判断是否已存在秒杀
	 * @return
	 */
	@ResponseBody
	@GetMapping("/seckill/test")
	public Result<Integer> getIsSeckillExist(){
		//设置新活动前，判断旧活动是否已结束，选择是否将旧活动取消
		if (gss.isSeckillExist()) {
			return Result.error(CodeMsg.SECKILL_NOT_EMPTY);
		}else{
			return Result.success(1);
		}
	}

	/**
	 * 设置定时降价拍卖
	 * @param req
	 * @param auction
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/auction/set", method = RequestMethod.POST)
	public Result<Integer> setNewAuction(HttpServletRequest req, @Validated Auction auction) {

		Integer goodsId = auction.getGoodsId();
		BigDecimal auctionOriginPrice = auction.getAuctionOriginPrice();
		BigDecimal auctionBottomPrice = auction.getAuctionBottomPrice();
		BigDecimal auctionPricespan = auction.getAuctionPricespan();
		Date auctionBeginTime = auction.getAuctionBeginTime();
		Date auctionEndTime = auction.getAuctionEndTime();
		Integer auctionTimespan = auction.getAuctionTimespan();

		//验证参数
		if(auctionBeginTime.before(new Date()) || auctionEndTime.before(auctionBeginTime)){
			return Result.error(CodeMsg.AUCTION_TIME_ERROR);
		}
		if (auctionOriginPrice.compareTo(auctionBottomPrice)<=0 ||
				auctionPricespan.compareTo(auctionOriginPrice.subtract(auctionBottomPrice))>=0) {
			return Result.error(CodeMsg.WRONG_PRICE);
		}

		//将auction存入表
		auction.setAuctionNowPrice(auctionOriginPrice);
		Integer auctionId = as.setAuction(auction);
		
		//将商品设为拍卖商品，并从普通商品中下架
		Integer set = gss.setGoodsAuction(goodsId, 1);
		if(set==0) {
			return Result.error(CodeMsg.MYSQL_CRUD_FAIL);
		}
		
		//设置定时降价任务
		Timer priceTimer = new Timer();
		priceTimer.scheduleAtFixedRate(new AuctionPriceTimerTask(priceTimer, auctionId, auctionEndTime, auctionOriginPrice, auctionBottomPrice, auctionPricespan),
				auctionBeginTime, auctionTimespan*60*1000);
		logger.info("New auction is set to " + auctionBeginTime);
		//设置定时检查过期订单任务
		Timer orderTimer = new Timer();
		orderTimer.scheduleAtFixedRate(new AuctionOrderTimerTask(orderTimer, auctionId), auctionBeginTime, orderPeriod);

		return Result.success(1);
	}

	/**
	 * 设置新一期秒杀
	 * @param req
	 * @param seckill
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/seckill/set", method = RequestMethod.POST)
	public Result<Integer> setNewSeckill(HttpServletRequest req, @Validated Seckill seckill) {

		//将seckill存入表
		Date seckillBeginTime = seckill.getSeckillBeginTime();
		if(seckillBeginTime.before(new Date())){
			return Result.error(CodeMsg.SECKILL_TIME_ERROR);
		}
		seckill.setTotalCount(seckill.getSeckillCount());
		Integer seckillId = ss.setSeckill(seckill);

		//将商品设为拍卖商品，并从普通商品中下架
		Integer set = gss.setGoodsSeckill(seckill.getGoodsId(), 1);
		if(set==0) {
			return Result.error(CodeMsg.MYSQL_CRUD_FAIL);
		}

		//设置定时检查过期订单任务
		Timer orderTimer = new Timer();
		orderTimer.scheduleAtFixedRate(new SeckillOrderTimerTask(orderTimer, seckillId), seckillBeginTime, orderPeriod);

		return Result.success(1);
	}


	/**
	 * 增加今日特价商品
	 * @param req
	 * @param goodsId
	 * @param onsalePrice
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/onsale/set", method = RequestMethod.POST)
	public Result<Integer> addOnsaleGoods(HttpServletRequest req, Integer goodsId, BigDecimal onsalePrice) {

		Onsale onsale = new Onsale();
		if (goodsId==null||onsalePrice==null) {
			return Result.error(CodeMsg.PARAM_ABSENCE);
		}
		onsale.setGoodsId(goodsId);
		onsale.setOnsalePrice(onsalePrice);
		onsale.setLimitTimes(-1);
		//将onsale存入表
		os.addOnsale(onsale);
		//将商品设为特价商品
		Integer set = gss.setGoodsOnsale(goodsId, 1);
		if(set==0) {
			return Result.error(CodeMsg.MYSQL_CRUD_FAIL);
		}
		return Result.success(1);
	}


	/**
	 * 结束商品活动
	 * 秒杀：isClosed设为1, 并将goodsStat的isSeckill设为0, isUpper设为1
	 * 拍卖：auction_end_time设为现在, 并将goodsStat的isAuction设为0, isUpper设为1
	 * 特价：删去onsale表中对应位置，并将goodsStat的isOnsale设为0
	 * @param req
	 * @param goodsId
	 * @return
	 */
	@ResponseBody
	@GetMapping("/activity/stop")
	public Result<Integer> stopActivity(HttpServletRequest req, Integer goodsId) {
		//查询商品活动信息
		GoodsStat goodsStat = gss.selStatByGoodsId(goodsId);
		//判断是什么活动
		if (goodsStat.getIsSeckill()==1) {	//秒杀
			List<Seckill> seckillList = ss.getSeckillsByGoodsId(goodsId);
			for (Seckill seckill : seckillList) {
				if (seckill.getIsClosed()==0) {
					seckill.setIsClosed(1);
					ss.updateSeckill(seckill);
				}
			}
			goodsStat.setIsSeckill(0);
			goodsStat.setIsUpper(1);
			gss.updateGoodsStat(goodsStat);
		}else if (goodsStat.getIsAuction()==1) {	//拍卖
			List<Auction> auctionList = as.selAuctionByGoodsId(goodsId);
			for (Auction auction : auctionList) {
				Date nowTime = new Date();
				if (auction.getAuctionEndTime().after(nowTime)) {
					auction.setAuctionEndTime(nowTime);
					as.updateAuction(auction);
				}
			}
			goodsStat.setIsAuction(0);
			goodsStat.setIsUpper(1);
			gss.updateGoodsStat(goodsStat);
		}else if (goodsStat.getIsOnsale()==1) {	//特价
			List<Onsale> onsaleList = os.selOnsaleByGoodsId(goodsId);
			for (Onsale onsale : onsaleList) {
				os.deleteOnsale(onsale.getOnsaleId());
			}
			goodsStat.setIsOnsale(0);
			goodsStat.setIsUpper(1);
			gss.updateGoodsStat(goodsStat);
		}else {	//未参与活动
			Result.error(CodeMsg.GOODS_NO_ACTIVITY);
		}
		return Result.success(1);
	}


	/**
	 * 展示拍卖列表
	 * @param req
	 * @param model
	 * @param pageIndex
	 * @param num
	 * @param totalPages
	 * @param sort
	 * @param order
	 * @return
	 */
	@GetMapping("/auctionList")
	public String toAuctionList(HttpServletRequest req, Model model,
							Integer pageIndex, Integer num, Integer totalPages,
							Integer sort, Integer order ) {
		if (null == pageIndex) {
			pageIndex = 1;
		}
		if (null == num) {
			num = 15;
		}
		if (null == totalPages) {
			totalPages = as.getTotalPages(num);
		}
		PageModel<AuctionModel> auctionInfo = as.selAuctionPage(pageIndex, num, totalPages, sort, order);
		model.addAttribute("data", auctionInfo);
		return "auctionList";
	}


	/**
	 * 展示秒杀列表
	 * @param req
	 * @param model
	 * @param pageIndex
	 * @param num
	 * @param totalPages
	 * @param sort
	 * @param order
	 * @return
	 */
	@GetMapping("/seckillList")
	public String toSeckillList(HttpServletRequest req, Model model,
							Integer pageIndex, Integer num, Integer totalPages,
							Integer sort, Integer order ) {
		if (null == pageIndex) {
			pageIndex = 1;
		}
		if (null == num) {
			num = 15;
		}
		if (null == totalPages) {
			totalPages = ss.getTotalPages(num);
		}
		PageModel<SeckillModel> seckillInfo = ss.selSeckillPage(pageIndex, num, totalPages, sort, order);
		model.addAttribute("data", seckillInfo);
		return "seckillList";
	}


	/**
	 * 查看当前活动
	 * @param req
	 * @param model
	 * @return
	 */
	@GetMapping("/nowActivity")
	public String toNowActivity(HttpServletRequest req, Model model) {
		//当前拍卖
		AuctionShowModel auction = as.showAuctionGoodsInfo();
		//当前秒杀
		SeckillShowModel seckill = ss.showSeckillGoodsInfo();
		//当前今日特价
		List<OnsaleShowModel> onsaleList = os.showOnsaleGoodsList();
		model.addAttribute("auction", auction);
		model.addAttribute("seckill", seckill);
		model.addAttribute("onsaleList", onsaleList);
		return "nowActivity";
	}

	
}
